package com.zth.Controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.zth.entity.LayData;
import com.zth.util.ConfugUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
public class UploadController2 {

    @PostMapping("uploadFile3")
    @ResponseBody
    public LayData uploadFile3(MultipartFile file, HttpServletRequest request) {





        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConfugUtil.END_POINT;
        // oss-cn-beijing.aliyuncs.com
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConfugUtil.ACCESS_SS_ID;
        String accessKeySecret = ConfugUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConfugUtil.BUCKET_NAME;
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

        // 新的名字
        String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
        // 无标题.png  1.3.4.5.jpg
        // +.JPG  PNG JEPG
        // 获取原来的文件的后缀 oldname
        String oldname = file.getOriginalFilename();
        int i = oldname.lastIndexOf(".");
        String suffixname = oldname.substring(i);
        //System.out.println("suffixname = " + suffixname);
        String newname = s + suffixname;
        //System.out.println("newname = " + newname);


        String objectName = newname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 填写字符串。
            String content = "Hello OSS";

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);

            // https://liuhongfei.oss-cn-beijing.aliyuncs.com/a1954baf-78ef-4dab-89f2-82652033ad29.jpg

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String picpath = "https://" + bucketName + "." + endpoint + "/" + objectName;

//        return "index";
        return  new LayData(picpath);
    }
}
